package com.TeaManage.servlet;

import com.TeaManage.bean.Admin;
import com.TeaManage.bean.Customer;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userType = request.getParameter("userType");

        // 验证必填字段
        if (username == null || username.trim().isEmpty() ||
            password == null || password.trim().isEmpty() ||
            userType == null || userType.trim().isEmpty()) {
            request.setAttribute("error", "用户名、密码和登录类型不能为空");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            return;
        }

        HttpSession session = request.getSession();

        if ("admin".equals(userType)) {
            // 管理员登录
            try {
                String sql = "SELECT * FROM admin WHERE name = ? AND password = ?";
                Admin admin = GokJDBCUtil.queryForObject(sql, Admin.class, username, password);

                if (admin != null) {
                    // 管理员登录成功
                    session.setAttribute("userType", "admin");
                    session.setAttribute("username", username);
                    session.setAttribute("admin", admin);
                    session.setAttribute("loginSuccess", "true");
                    response.sendRedirect("views/home.jsp");
                } else {
                    // 管理员登录失败
                    request.setAttribute("error", "管理员用户名或密码错误");
                    request.getRequestDispatcher("/views/login.jsp").forward(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error", "登录失败，请稍后重试");
                request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            }
        } else if ("customer".equals(userType)) {
            // 客户登录
            try {
                // 验证手机号格式
                if (!isValidPhone(username)) {
                    request.setAttribute("error", "请输入正确的手机号格式");
                    request.getRequestDispatcher("/views/login.jsp").forward(request, response);
                    return;
                }

                // 查询客户信息
                String sql = "SELECT * FROM customer WHERE phone = ? AND password = ? AND status = 1";
                Customer customer = GokJDBCUtil.queryForObject(sql, Customer.class, username, password);

                if (customer != null) {
                    // 登录成功
                    session.setAttribute("userType", "customer");
                    session.setAttribute("customer", customer);
                    session.setAttribute("customerId", customer.getCustomer_id());
                    session.setAttribute("customerName", customer.getCustomer_name());
                    session.setAttribute("customerPhone", customer.getPhone());
                    session.setAttribute("loginSuccess", "true");
                    response.sendRedirect("views/user/index.jsp");
                } else {
                    // 检查用户是否存在
                    String checkSql = "SELECT * FROM customer WHERE phone = ?";
                    Customer existCustomer = GokJDBCUtil.queryForObject(checkSql, Customer.class, username);

                    if (existCustomer == null) {
                        request.setAttribute("error", "该手机号未注册，请先注册");
                    } else if (existCustomer.getStatus() == 0) {
                        request.setAttribute("error", "账号已被禁用，请联系管理员");
                    } else {
                        request.setAttribute("error", "密码错误");
                    }
                    request.getRequestDispatcher("/views/login.jsp").forward(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error", "登录失败，请稍后重试");
                request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("error", "无效的登录类型");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET请求重定向到登录页面
        response.sendRedirect("views/login.jsp");
    }

    private boolean isValidPhone(String phone) {
        // 简单的手机号验证：11位数字，以1开头
        String phonePattern = "^1[3-9]\\d{9}$";
        return phone != null && phone.matches(phonePattern);
    }
}